#include "bit_reader.h"
#include "defs.h"


void init_buffer(bitstream* pstream){
    pstream->length = 0;
    pstream->buffer = 0;
}

int read_bit(FILE* infile, bitstream* pstream){

    unsigned char input;
    int count;

    count = fread(&input, sizeof(unsigned char), 1, infile);

    if (count > 0) {
        pstream->length = 8;
        pstream->buffer = input;
        //printf("Inside read_bit:%x\n", input);       
    } else {

    }
    
    return pstream->length;

}

void show_bit(bitstream* pstream){

    printf("%x ", pstream->buffer);

}

int size_to_width(int size){
    /*
    * 256 => 8
    * 257 => 9
    * 512 => 9
    * 513 => 10
    */
    int i;
    for(i = 8; i <31; i++){
        if(size <= (1 << i))
            break;
    }
    if(i >= SIZE_LENGTH)
        return SIZE_LENGTH;
    else
        return i;
    return 0;
}

int read_buffer(bitstream* pstream, int width, FILE* infile){
    int result = 0;
    int filled = 0;
    unsigned char cut = 0;
    int to_read = 0;

    if(pstream-> length > width){
        cut = pstream->buffer << (8 - width);
        cut = cut >> (8 - width);
        pstream->buffer = pstream->buffer >> width;
        pstream->length = pstream->length - width;
        result = cut; 
    } else {
        result = pstream->buffer;
        filled += pstream->length;
        //printf("%x\n", pstream->buffer);
        //printf("Out: %d\n", result);
        while(filled < width){
            //printf("Filled %d\n", filled);
            //printf("Width %d\n", width);
            read_bit(infile, pstream);
            to_read = width - filled > 8 ? 8: width - filled;
            //show_bit(pstream);
            cut = pstream->buffer << (8 - to_read);
            cut = cut >> (8 - to_read);
            //printf("Cut: %d\n", cut);
            result |= (cut << filled);
            filled += to_read;
            pstream->length -= to_read;
            pstream->buffer = pstream->buffer >> to_read;
            //printf("In: %d\n", result);
            //printf("%x\n", pstream->buffer);

        }
    }
    //printf("\n\n");
    return result;
}